#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <cstdio>
#include <unistd.h>         //syscall的头文件
#include <sys/syscall.h>    //syscall的头文件
#include <atomic>

class ThreadPool {
public:
    ThreadPool(int numThreads) : stop(false) 
    {
        for (int i = 0; i < numThreads; ++i) 
        {
            threads.emplace_back([this] 
            {
                while (true) 
                {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(mutex);
                        //如果stop为true 或 task为非空，往下执行
                        condition.wait(lock, [this] { return stop || !tasks.empty(); });
                        //如果stop为true，但task不为空，要继续执行任务
                        //直到任务队列为空才返回
                        if (stop && tasks.empty()) 
                        {
                            return;
                        }
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    //执行任务
                    task();
                }
            });
        }
    }

    ~ThreadPool() 
    {
        stop = true;
        //唤醒所有线程执行任务，所有任务被执行完毕，子线程才允许返回
        condition.notify_all();
        for (std::thread& thread : threads) 
        {
            thread.join();
        }
    }

    template<typename F, typename... Args>
    void add_task(F&& f, Args&&... args) 
    {
        std::function<void()> task(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
        {
            std::unique_lock<std::mutex> lock(mutex);
            tasks.emplace(std::move(task));
        }
        condition.notify_one();
    }

private:
    std::vector<std::thread> threads;
    std::queue<std::function<void()>> tasks;
    std::mutex mutex;
    std::condition_variable condition;
    std::atomic<bool> stop;
};

int main() {
    ThreadPool pool(4);
    for (int i = 0; i < 8; ++i) 
    {
        pool.add_task([i] 
        {
            printf("Task(%d) is running in thread(%d)\n",i,syscall(SYS_gettid));
            std::this_thread::sleep_for(std::chrono::seconds(1));
            printf("Task(%d) is done\n",i);
        });
    }
    return 0;
}